google.load("feeds", "1");

(function($) {
	$(document).ready(function() {
		 $('#timeline').empty();
	     tweetList();
         tweetUserList();
	     facebookList(1);
		//$('#add-twitter-account').button({
		//	icons: { primary: 'ui-icon-plus'}
		//});
		$('#add-twitter-account').click(function(){
			     		$.oauthpopup({
						            path:'/auth/login/twt?add=true',
						            callback: tweetList,
						            windowOptions: 'location=0,status=0'
						});
					});
		//$('#add-facebook-account').button({
		//	icons: { primary: 'ui-icon-plus'}
		//});
		$('#add-facebook-account').click(function(){
			     		$.oauthpopup({
						            path:'/auth/login/fb?add=true',
						            callback: facebookList,
						            windowOptions: 'location=0,status=0'
						});
					});
		
		$('#rss-list input[type="checkbox"]').click(function(){
			if(this.checked){
				rssList(this.value);
			}
		});
	
		$('#add-rss-feed').button({
			icons: { primary: 'ui-icon-plus'}
		});
		$('#add-rss-feed').click(function(){
			var url=prompt("RSSフィードのURLを入力してください","http://");
            rssList(url);
		});
		$('#add-scrapbook-button').button({
			icons: { primary: 'ui-icon-plus'}
		});
		$('#add-scrapbook-button').click(function(){
			var name = prompt("スクラップブックの名前を入力してください",""); 
			$.post("/scrapbook/add",
				{'name':name}, function(data){
					console.log(data);
					$('#scrap-list').append($('<li id="' + data.key + '"style="background-image:url(image/Bookmarks2.png)">' + data.name + '</li>'));
				});
		});
		$('#recent-clipbook-list').dialog({'autoOpen':false, 'width':600})
		$('#show-recent-clipbook-list').click(function(){

			$('#recent-clipbook-list').empty();
			$.get('scrapbook/list',function(data){
				$.each(data, function(){
					//TODO:
                    var html = $('#clipbook-template').tmpl(this);
                    html.find(".clipbook-content").append(renderScrapBookContent(this));
					$('#recent-clipbook-list').append(html);
					
				});
			});
			$('#recent-clipbook-list').dialog('open');
		});
		
		$.get('/scrapbook/list',function(data){
			console.log(data);
			$.each(data, function(){
				$('#scrap-list').append($('<li id="' + this.key + '"style="background-image:url(image/Bookmarks2.png)">' + this.name + '</li>'));
			});
		});
		$('#scrap-list li').livequery(function() {
			$(this).droppable({
				tolerance: "pointer",
				drop: function(ev, ui) {
					var id = ui.draggable.attr('id').split(':');
					var service = id[0];
					var fb_message_id = id[1].split('_');
					var url = 'http://www.facebook.com/' + fb_message_id[0] + '/posts/' + fb_message_id[1];
					var content = ui.draggable.data('content');
					console.log(content);
					$.post('/scrapbook/addentry',
							{'key':$(this).attr('id'),'service':service, 'url': url, 'content': JSON.stringify(content)});

					$(this).css('border','2px solid white');
				},
				over: function(ev, ui){
					$(this).css('border','2px solid blue');
				},
				out: function(ev, ui){
					$(this).css('border','2px solid white');
				}
			});
			$(this).click(function(){
				var key = $(this).attr('id');
				$('#pankuzulist').text("クリップブック「" + $(this).text() + "」");
				$('#clipbook-header').show();
				$.get('/scrapbook/listentry?key=' + key, function(data){
					$('#timeline').empty();
					$.each(data, function(){
						insertHTML(renderScrapBookContent(this));
					});
				});
			})
	    }); 
		
		$('#back-timeline').click(function(){
			$('#clipbook-header').hide();
			 $('#timeline').empty();
			 tweetList();
	         tweetUserList();
		     facebookList(1);
		});
		
		$('.feed-item').livequery(function() {
			$(this).draggable({helper:'clone'});
	    }); 
	});
	
})(jQuery);

var insertHTML = (function() {
	    	    return function(html) {
	    	        if ($('#timeline').children().size() === 0) {
                        $(html).appendTo('#timeline');
                        return;
                    }
	    	        var tmpStr;
	    	        $('#timeline').children().each(function() {
	    	            if ($(html).data('date') > $(this).data('date')) {
	    	                $(this).before(html);
	    	                return false;
	    	            }
	    	            tmpStr = this;
	    	        });
	    	        $(tmpStr).after(html);
	    	    }	    	    
})();

var tweetList = (function() {
	    	    return function() {
                    tweetListButtonClear();
                    
	    	        $.getJSON("/twt/getList", function(json) {
	    	            if (json.error) {

	    	            }
	    	            else {
                            $('#add-twitter-account').attr("checked", "checked");
	    		            //console.log(json);
	    		            $.each(json, function() {
	    	                    insertHTML( renderTwitterEntry($(this)[0]) );
	    		            });
	    		       }
	    	        });
	    	    }
})();

var tweetListButtonClear = function() {
    var display = $("ul.the_menu").css('display');
    if (display === 'block') {
        $("ul.the_menu").css('display', 'None');
        $('input:radio[name=twitter-radio].menu_class').attr("checked", false);
        $("ul.the_menu").children().each(function() {
            $(this).find("input").attr("checked", false);
        });
    }

}

var tweetUserList = (function() {
    return function() {
        $.getJSON("/twt/userList", function(json) {
            if (json.error) {

            }
            else {
                $('.menu_class').click(function () {
                    var display = $("ul.the_menu").css('display');
	                $('ul.the_menu').slideToggle('medium');

                    if (display === 'block') {
                        $('input:radio[name=twitter-radio].menu_class').attr("checked", false);
                    }
                });

                $.each(json, function() {
                    //$("ul.the_menu").append('<li><a href="#' + this.id +'">' + this.name + '</a></li>');
                    $("ul.the_menu").append('<li><input type="radio" name="twitter-list" value="' + this.id +'">' + this.name + '</li>');
                    console.log(json);
                });

                $("ul.the_menu").children().each(function() {
                    $(this).find("input").click(function() {
                        $('#timeline').empty();
                        tweetUserListStatus($(this).val());
                        facebookList(1);
                    });
                });
            }
        });
    }
})();

var tweetUserListStatus = (function() {
    return function(listId) {
        $.getJSON("/twt/userListStatus/" + listId, function(json) {
            if (json.error) {

            }
            else {
            	$.each(json, function() {
                    insertHTML( renderTwitterEntry($(this)[0]) );
	    		});
            }
        });
    }
})();



var rssList = (function() {
    return function(url) {
        var feed = new google.feeds.Feed(url);
        feed.setNumEntries(20);
        feed.load(function(result) {
        	if (!result.error) {
            	$.post('/rss/add', {'url':url, 'title':	result.feed.title});
                for (var i = 0; i < result.feed.entries.length; i++) {
                    var entry = result.feed.entries[i];
                	console.log(entry);
                    var tmpDate = new Date(entry.publishedDate);
                    console.log(tmpDate);
	    	        entry.publishedDate = tmpDate.toLocaleString();
	    	        entry.feed_title = result.feed.title;
                    var html = $("#rss-feed-template").tmpl(entry);
                    html.find(".tweet-text").append(entry.content);
                    html.data('date', tmpDate);
                    insertHTML(html);
                }
            }
        });
    }
})();

function renderScrapBookContent(data){

	var html;
	if(data.service =='facebook')
		html = renderFacebookEntry(eval("(" + data.content + ")"));
	else if(data.service =='twitter')
		html = renderTwitterEntry(eval("(" + data.content + ")"));
	else
		console.log("TODO RSS");
	
	console.log(html);
	return html;
}

function renderTwitterEntry(data){
	console.log("AAA", data);
    var tmpDate = new Date(data.createdAt);
    tmpDate = new Date(tmpDate.getTime() + 9 * 60 * 60 * 1000);
    //data.createdAt = tmpDate.toLocaleString();
	var html = $("#twitter-status-template").tmpl(data);
	console.log(html);
	html.data('date', tmpDate);
	html.data('content', data);
	return html;
}

function renderFacebookEntry(data){
	console.log(data);
    var tmpDate = isodate.parse(data.updated_time.replace(/\+.*/, ''));
    tmpDate = new Date(tmpDate.getTime() + 9 * 60 * 60 * 1000);
    //data.updated_time = tmpDate.toLocaleString();
	var html;
	if(data.type == 'status'){
		html = $("#facebook-status-template").tmpl(data);
	}else if(data.type == 'link'){
			console.log(data);
		html = $("#facebook-link-template").tmpl(data);
	}else if(data.type == 'photo'){
		html = $("#facebook-photo-template").tmpl(data);
		}
	html.data('date', tmpDate);
	html.data('content', data);
	return html;
}

function facebookList(){


    $.getJSON("/fb/newsfeed", function(json) {
                    //$('#message-list-container').empty();
                    if(json.error){
                        //$('#go-to-facebook-link-container').show();
                    }else{
                        $('#add-facebook-account').attr("checked", "checked");
                        //jQuery templateを使うにはJSONの整形が必要
                        $.each(json.data, function() {
                        	insertHTML(renderFacebookEntry(this) );
                        });
                  }
    });
}